package middleware

import (
	"encoding/json"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/log"
	"github.com/crack007/go-im/src/common/component"
	"github.com/crack007/go-im/src/common/constant"
	"github.com/crack007/go-im/src/common/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func AuthMiddleware(ctx *gin.Context) {
	header := ctx.GetHeader("Authorization")
	if header == "" {
		ctx.AbortWithStatus(403)
		return
	}
	header = strings.ReplaceAll(header, "Bearer ", "")
	payload, err := component.Jwt.Parse(header)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		ctx.Abort()
		return
	}
	userModel := model.NewUserModel()
	err = json.Unmarshal([]byte(payload.Data), userModel)
	if err != nil {
		ctx.JSON(200, gin.H{
			"code": 500,
			"msg":  err.Error(),
			"data": nil,
		})
		ctx.Abort()
		return
	}
	ctx.Set(constant.REQUEST_USER, userModel)
	if goose.GetLogger().GetLogLevel() <= log.LEVEL_DEBUG {
		ctx.Header("User-id", strconv.Itoa(int(userModel.Id)))
	}
	ctx.Next()
}
